// 对接文档：https://help.aliyun.com/zh/captcha/captcha2-0/user-guide/client-access

interface VerifyCallback {
    (verifyParam: string): Promise<{ captchaResult: boolean }>;
}
interface Captcha {
    captchaVerifyCallback?: VerifyCallback;
}

let captcha: Captcha = null;
let pendingCallback = null;

let $button = document.createElement("button");
$button.id = "aliyunCaptcha-button";
$button.style.display = "none";
document.body.append($button);

let w: any = window;
if(w.initAliyunCaptcha) {
w.initAliyunCaptcha({
    SceneId: "1f4ijb1a", // 场景id
    mode: "popup", // 弹出式
    button: "#aliyunCaptcha-button", // 触发显示的按钮id
    getInstance(instance: Captcha) {
        // 保存实例
        captcha = instance;
        if (pendingCallback) {
            captcha.captchaVerifyCallback = pendingCallback;
            pendingCallback = null;
            $button.click();
        }
    },
});
}

export function showCaptcha(callback) {
    return new Promise((resolve) => {
        // 回调函数
        const cb = async function (verifyParam) {
            let captchaResult = await callback(verifyParam, resolve);
            return { captchaResult };
        };
        // 已初始化
        if (captcha) {
            captcha.captchaVerifyCallback = cb;
            $button.click();
        } else {
            // 当前还未初始化，暂存
            pendingCallback = cb;
        }
    });
}
